import json5
import json
import copy
SIGNING_DEFAULT_TEMPLATE = {
    "name": "default",
    "type": "HarmonyOS",
    "material": {}
}
SIGNING_TEMPLATE = {
    "name": "",
    "type": "HarmonyOS",
    "material": {}
}

BUILD_MODE_SET_TEMPLATE = {"name": "" }

BUILD_PROFILE_JSON = '/build-profile.json5'

def changeSigningInfo(projectPath, signingConfig, signingName):
    with open(f"{projectPath}{BUILD_PROFILE_JSON}", 'r') as f:
        data = json5.load(f)
        if isinstance(signingConfig, str):
            signingConfigJson = json5.loads(signingConfig)
            # 修改signingConfigs
            signingConfigs = data['app']['signingConfigs']
            SIGNING_TEMPLATE['material'] = signingConfigJson
            SIGNING_TEMPLATE['name'] = signingName
            if len(signingConfigs) > 0:
                isExist = False
                for item in signingConfigs:
                    if item['name'] == signingName:
                        item['material'] = signingConfigJson
                        isExist = True
                if (isExist == False):
                    signingConfigs.append(SIGNING_TEMPLATE)
            else:
                SIGNING_DEFAULT_TEMPLATE['material'] = signingConfigJson
                signingConfigs.append(SIGNING_DEFAULT_TEMPLATE)
                signingConfigs.append(SIGNING_TEMPLATE)

            print(f"signingConfigs:{signingConfigs}")
            data['app']['signingConfigs'] = signingConfigs


        #修改products
        products = data['app']['products']
        if len(products) > 0:
            isExist = False
            for item in products:
                if item['name'] == signingName:
                    item['signingConfig'] = signingName
                    isExist = True
            if isExist == False:
                temp = copy.deepcopy(products[0])
                temp['name'] = signingName
                temp['signingConfig'] = signingName
                products.append(temp)
                data['app']['products'] = products
            print(f"products:{products}")
        else:
            print('build-profile.json5 中没有products节点，无法修改签名信息')
            exit(0)

        # 修改buildModeSet
        buildModeSet = data['app']['buildModeSet']
        isExist = False
        if len(buildModeSet) > 0:
            for item in buildModeSet:
                if item['name'] == signingName:
                    isExist = True
            if isExist == False:
                temp = copy.deepcopy(buildModeSet[0])
                temp['name'] = signingName
                buildModeSet.append(temp)
                data['app']['buildModeSet'] = buildModeSet
                print(f"buildModeSet:{buildModeSet}")
        else:
            BUILD_MODE_SET_TEMPLATE['name'] = signingName
            data['app']['buildModeSet'].append(BUILD_MODE_SET_TEMPLATE)

        # 修改modules targets applyToProducts
        modules = data['modules']

        for item in modules:
            if item['name'] == 'entry':
                targets = item['targets']
                for t in targets:
                    if t['name'] == 'default':
                        applyToProducts = t['applyToProducts']
                        isExist = False
                        for p in applyToProducts:
                            if p == signingName:
                                isExist = True

                        if isExist == False:
                            applyToProducts.append(signingName)
                            t['applyToProducts'] = applyToProducts

    print(f"signingConfigs:data:{data}")
    with open(f"{projectPath}{BUILD_PROFILE_JSON}", 'w') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
